import { useState,useRef,useEffect } from "react"

function StopWatch(){
    const [isRunning,setIsRunning] = useState(false)
    // 经过的事件
    const [elapsedTime,setElapsedTime] = useState(0)
    const startTimeRef = useRef(null)
    const intervalIDRef = useRef(null)

    useEffect(()=>{
        if(isRunning){
            intervalIDRef.current = setInterval(()=>{
                // 计算经过的时间
                setElapsedTime(Date.now() - startTimeRef.current)
            },10)
        }
        return () => {
            clearInterval(intervalIDRef.current)
        }
    },[isRunning])

    const start = () => {
        // 方便停止的时候，再继续点击开始，方便记录原始的起始时间
        startTimeRef.current = Date.now() - elapsedTime
        setIsRunning(true)
    }
    const reset = () => {
        setIsRunning(false)
        setElapsedTime(0)
    }
    const stop = () => {
        setIsRunning(false)
    }

    const formatTime = () => {
        let minutes = Math.floor(elapsedTime / (1000 * 60) % 60)
        let seconds = Math.floor(elapsedTime / 1000 % 60)
        let milliseconds = Math.floor(elapsedTime % 1000 / 10)

        minutes = String(minutes).padStart(2,'0')
        seconds = String(seconds).padStart(2,'0')
        milliseconds = String(milliseconds).padStart(2,'0')
        return `${minutes}:${seconds}:${milliseconds}`
    }
    return (
        <div className="stopwatch-container">
            <p className="display">{formatTime()}</p>
            <div className="btns-control">
                <button onClick={start} className="start-button">Start</button>
                <button onClick={reset} className="reset-button">Reset</button>
                <button onClick={stop} className="stop-button">Stop</button>
            </div>
        </div>
    )
}

export default StopWatch